package com.talent.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.talent.common.PageResult;
import com.talent.interceptor.BaseContext;
import com.talent.mapper.OperationLogMapper;
import com.talent.mapper.UserMapper;
import com.talent.pojo.dto.OperationLogDetailDTO;
import com.talent.pojo.entity.OperationLog;
import com.talent.pojo.entity.User;
import com.talent.service.OperationLogService;
import com.talent.utils.OperationLogUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;

/**
 * 操作日志服务实现类
 */
@Slf4j
@Service
public class OperationLogServiceImpl implements OperationLogService {

    @Autowired
    private OperationLogMapper operationLogMapper;

    @Autowired
    private UserMapper userMapper;

    /**
     * 新增操作日志（简单版本）
     */
    @Override
    public void save(String action) {
        Long currentUserId = BaseContext.getCurrentUserId();
        if (currentUserId == null) {
            return; // 未登录用户不记录日志
        }

        User user = userMapper.getById(currentUserId);
        if (user == null) {
            return;
        }

        OperationLog operationLog = new OperationLog();
        operationLog.setUserId(currentUserId);
        operationLog.setUsername(user.getName());
        operationLog.setPhone(user.getPhone());
        operationLog.setDepartment(user.getDepartment());
        operationLog.setAction(action);

        operationLogMapper.insert(operationLog);
    }

    /**
     * 新增操作日志（详细版本）
     */
    @Override
    public void saveDetail(OperationLogDetailDTO operationLogDetail) {
        try {
            Long currentUserId = BaseContext.getCurrentUserId();
            if (currentUserId == null) {
                return; // 未登录用户不记录日志
            }

            User user = userMapper.getById(currentUserId);
            if (user == null) {
                return;
            }

            OperationLog operationLog = new OperationLog();
            operationLog.setUserId(currentUserId);
            operationLog.setUsername(user.getName());
            operationLog.setPhone(user.getPhone());
            operationLog.setDepartment(user.getDepartment());
            operationLog.setAction(operationLogDetail.getAction());
            operationLog.setActionDetail(operationLogDetail.getActionDetail());
            operationLog.setResourceType(operationLogDetail.getResourceType());
            operationLog.setResourceId(operationLogDetail.getResourceId());
            operationLog.setResourceName(operationLogDetail.getResourceName());
            operationLog.setOldData(OperationLogUtils.toJsonString(operationLogDetail.getOldData()));
            operationLog.setNewData(OperationLogUtils.toJsonString(operationLogDetail.getNewData()));
            operationLog.setIpAddress(operationLogDetail.getIpAddress());
            operationLog.setUserAgent(operationLogDetail.getUserAgent());

            operationLogMapper.insert(operationLog);
        } catch (Exception e) {
            log.error("保存操作日志失败", e);
        }
    }

    /**
     * 分页查询操作日志
     */
    @Override
    public PageResult<OperationLog> pageQuery(Integer page, Integer pageSize, String username, 
                                              String phone, String action, LocalDate startDate, LocalDate endDate) {
        PageHelper.startPage(page, pageSize);
        
        LocalDateTime startDateTime = startDate != null ? startDate.atStartOfDay() : null;
        LocalDateTime endDateTime = endDate != null ? endDate.atTime(23, 59, 59) : null;
        
        Page<OperationLog> p = (Page<OperationLog>) operationLogMapper.pageQuery(
                username, phone, action, startDateTime, endDateTime);

        return new PageResult<>(p.getResult(), p.getTotal(), page, pageSize);
    }
}
